<template>
<van-cell-group>

  <div class="van-cell van-cell--required van-hairline van-field" :class="{'van-cell--center van-field--error': errors.has('oldSafePassword')}">
    <div class="van-cell__title"><span>原安全密码</span></div>
    <div class="van-cell__value">
      <input v-model="formFields.oldSafePassword" v-validate="'required|min:6'" name="oldSafePassword" type="password" placeholder="请输入原安全密码" class="van-field__control">
      <div v-if="errors.has('oldSafePassword')" class="van-field__error-message">{{ errors.first('oldSafePassword') }}</div>
    </div>
  </div>

  <div class="van-cell van-cell--required van-hairline van-field" :class="{'van-cell--center van-field--error': errors.has('newSafePassword')}">
    <div class="van-cell__title"><span>新安全密码</span></div>
    <div class="van-cell__value">
      <input v-model="formFields.newSafePassword" v-validate="'required|min:6'" name="newSafePassword" type="password" placeholder="请输入新安全密码" class="van-field__control">
      <div v-if="errors.has('newSafePassword')" class="van-field__error-message">{{ errors.first('newSafePassword') }}</div>
    </div>
  </div>

  <div class="van-cell van-cell--required van-hairline van-field" :class="{'van-cell--center van-field--error': errors.has('password')}">
    <div class="van-cell__title"><span>登陆密码</span></div>
    <div class="van-cell__value">
      <input v-model="formFields.password" v-validate="'required|min:6'" name="password" type="password" placeholder="请输入登陆密码" class="van-field__control">
      <div v-if="errors.has('password')" class="van-field__error-message">{{ errors.first('password') }}</div>
    </div>
  </div>

  <van-button v-if="!isDisabled" size="large" type="primary" @click="onSubmit">提交</van-button>
</van-cell-group>
</template>

<script>
import qs from 'qs';
import { NavBar, Field, CellGroup, Button, Toast } from 'vant';
import ajaxVant from '../../../utils/ajaxVant';
import auth from '../../../utils/auth';

export default {
  components: {
    [NavBar.name]: NavBar,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button
  },
  data() {
    return {
      isDisabled: false,
      formFields: {
        oldSafePassword: '',
        newSafePassword: '',
        password: ''
      }
    };
  },
  methods: {
    onSubmit() {
      var _this = this;
      _this.$validator.validateAll().then((result) => {
        if (result) {
          auth.getToken().then(function(token) {
            ajaxVant.put('/user/safePassword?token=' + token, qs.stringify(_this.formFields)).then(function(data) {
              if (data !== false) {
                Toast('提交成功');

                setTimeout(() => {
                  Toast.clear();
                  _this.$router.push({ name: 'user' });
                }, 1000);
              }
            });
          });
        }
      });
    }
  }
};

</script>